package tony.com.xframe;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Tony on 2016-01-03.
 */
public class SMSBroadcastReceiver extends BroadcastReceiver {
    private IntentFilter filter2;
    private String strContent;
    private static int patternCodeLegth = 0;//判断是几位的验证码
    private String patternCoder;

    private static MessageCodeListener messageCodeListener;
    private static String fromCode;//用于区别知道号码发来的验证码
    private static String code;//用于区别知道号码发来的验证码

    public SMSBroadcastReceiver() {
    }

    /**
     * @param messageCodeListener
     * @param fromCode            //用于区别知道号码发来的验证码
     * @param patternCodeLegth    ;//判断是几位的验证码
     */
    public SMSBroadcastReceiver(MessageCodeListener messageCodeListener, String fromCode, int patternCodeLegth) {
        this.messageCodeListener = messageCodeListener;
        this.fromCode = fromCode;
        this.patternCodeLegth = patternCodeLegth;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        filter2 = new IntentFilter();
        filter2.addAction("android.provider.Telephony.SMS_RECEIVED");
        filter2.setPriority(Integer.MAX_VALUE);


        Object[] objs = (Object[]) intent.getExtras().get("pdus");
        for (Object obj : objs) {
            byte[] pdu = (byte[]) obj;
            SmsMessage sms = SmsMessage.createFromPdu(pdu);
            // 短信的内容
            String message = sms.getMessageBody();
            Log.d("logo", "message     " + message);
            // 短息的手机号。。+86开头？
            String from = sms.getOriginatingAddress();
            Log.d("logo", "from     " + from);


            if (!TextUtils.isEmpty(from)) {
                if (fromCode.equals(from)) {
                     code = patternCode(message);
                    if (!TextUtils.isEmpty(code)) {
                        strContent = code;
                        messageCodeListener.getMessageCode(code);
//
                    }
                }
            }
        }
    }

    /**
     * 匹配短信中间的6个数字（验证码等）
     *
     * @param patternContent
     * @return
     */
    private String patternCode(String patternContent) {
        patternCoder = "(?<!\\d)\\d{" + patternCodeLegth + "}(?!\\d)";
        if (TextUtils.isEmpty(patternContent)) {
            return null;
        }

        Pattern p = Pattern.compile(patternCoder);
        Matcher matcher = p.matcher(patternContent);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }

    public interface MessageCodeListener {
        String getMessageCode(String code);
    }
}
